<template>
  <page-header-wrapper :title="false">
    <a-card title="我的发票">
      <a-tabs type="card" @change="onTabs">
        <a-tab-pane key="10">
          <span slot="tab">
            <a-badge :count="invoiceNum.invoiceDshCounts">待审核</a-badge>
          </span>
        </a-tab-pane>
        <a-tab-pane key="30">
          <span slot="tab">
            <a-badge :count="invoiceNum.invoiceZsbgCounts">组审不过</a-badge>
          </span>
        </a-tab-pane>
        <a-tab-pane key="50">
          <span slot="tab">
            <a-badge :count="invoiceNum.invoiceCsbgCounts">财审不过</a-badge>
          </span>
        </a-tab-pane>
        <a-tab-pane key="40">
          <span slot="tab">
            <a-badge :count="invoiceNum.invoiceYkpCounts">已开票</a-badge>
          </span>
        </a-tab-pane>
      </a-tabs>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="申请时间">
                <a-range-picker @change="onCreateAt" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <s-table
        bordered
        ref="table"
        :row-key="(record) => record.id"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :columns="invoiceColumns"
        :data="invoiceData"
        :alert="true"
      >
        <template slot="contract_no" slot-scope="text,record">
          <a-button v-if="text == '合并合同'" type="link" @click="toDetail(record.id)">{{ text }}</a-button>
          <a-button v-else type="link" @click="$router.push({ name: 'ContractDetail', params: { cid: record.contract_id } })">{{ text }}</a-button>
        </template>
        <template slot="invoice_type" slot-scope="text">
          <a-tag v-if="text == 1" color="red">{{ typeOpts[text] }}</a-tag>
          <a-tag v-if="text == 2" color="blue">{{ typeOpts[text] }}</a-tag>
        </template>
        <template slot="header_type" slot-scope="text">
          <a-tag color="red">{{ headerOpts[text] }}</a-tag>
        </template>
        <template slot="amount" slot-scope="text">
          <a-tag color="red">{{ text }}</a-tag>
        </template>
        <template slot="invoice_taxation" slot-scope="text">
          <a-tag color="red">{{ text }}</a-tag>
        </template>
        <template slot="invoice_taxation" slot-scope="text">
          <a-tag color="red">{{ text }}</a-tag>
        </template>
        <template slot="status" slot-scope="text">
          <a-tag color="red">{{ statusOpts[text] }}</a-tag>
        </template>
        <template slot="tm_name" slot-scope="text,record">
          {{ text }}{{ record.pt_name }}
        </template>
        <template slot="company_name" slot-scope="text,record">
          {{ text }}({{ record.tax_point }}%)
        </template>
        <template slot="express_name" slot-scope="text,record">
          <div v-if="text">{{ text }}({{ record.express_num }})</div>
        </template>
        <template slot="action" slot-scope="text,record">
          <a-badge dot v-if="record.is_read == 0">
            <a-button size="small" type="primary" @click="toDetail(record.id)">查看</a-button>
          </a-badge>
          <a-button v-else size="small" type="primary" @click="toDetail(record.id)">查看</a-button>
          <div style="display: inline-block; margin-left: 5px;" v-if="record.status == 30 || record.status == 50"><a-button size="small" type="danger" @click="editInvoice(record.id)">重新开票</a-button></div>
        </template>
      </s-table>
      <a-modal
        destroy-on-close
        title="填写发票信息"
        v-model="invoiceVisible"
        :width="700"
        :mask-closable="false"
        @ok="onSubmit"
      >
      <a-form-model
        ref="ruleForm"
        :model="invoiceForm"
        :rules="invoiceRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="选择开票公司" prop="company_id">
          <a-select
            show-search
            placeholder="选择开票公司"
            v-model="invoiceForm.company_id"
            :filter-option="filterOption"
            @change="onChange"
          >
            <a-select-option :disabled="item.stock == 0" v-for="item in companyOpts" :key="item.id" :value="item.id">{{ item.company_name }}(税点{{ item.tax_point }}%)(余票{{ item.stock }})</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-divider orientation="left">填写纳税人信息</a-divider>
        <a-form-model-item label="开票附件" prop="file_url">
          <a-upload
            accept=".docx,.doc"
            name="file"
            :multiple="true"
            :action="uploadUrl"
            :headers="header"
            @change="uploadChange"
          >
            <a-button> <a-icon type="upload" />附件</a-button>
            <a-button size="small" type="link" icon="download" @click="download">点击下载发票模版</a-button>
          </a-upload>
        </a-form-model-item>
        <!--        <a-form-model-item label="抬头类型" prop="header_type">-->
        <!--          <a-radio-group v-model="invoiceForm.header_type">-->
        <!--            <a-radio v-for="(item,index) in headerOpts" :key="index" :value="index" :disabled="index == 10 && invoiceForm.invoice_type == 20">-->
        <!--              {{ item }}-->
        <!--            </a-radio>-->
        <!--          </a-radio-group>-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="发票抬头" prop="header">-->
        <!--          &lt;!&ndash;          <template slot="help">&ndash;&gt;-->
        <!--          &lt;!&ndash;            <span style="color:#999">无需填写，与合同基本信息一致</span>&ndash;&gt;-->
        <!--          &lt;!&ndash;          </template>&ndash;&gt;-->
        <!--          <a-input v-model="invoiceForm.header" placeholder="输入发票抬头" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="发票类型" prop="invoice_type">-->
        <!--          <template slot="help">-->
        <!--            <span style="color:#999">无需填写，选择开票时自动选择</span>-->
        <!--          </template>-->
        <!--          <a-radio-group disabled v-model="invoiceForm.invoice_type" name="radioGroup">-->
        <!--            <a-radio v-for="(item,index) in typeOpts" :key="index" :value="index">{{ item }}</a-radio>-->
        <!--          </a-radio-group>-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="统一社会信用代码" prop="social_code">-->
        <!--          <a-input v-model="invoiceForm.social_code" placeholder="输入统一社会信用代码" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="开户银行名称" prop="bank_name">-->
        <!--          <a-input v-model="invoiceForm.bank_name" placeholder="输入开户银行名称" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="基本开户账号" prop="account_num">-->
        <!--          <a-input v-model="invoiceForm.account_num" placeholder="输入基本开户账号" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="注册场所地址" prop="register_address">-->
        <!--          <a-input v-model="invoiceForm.register_address" placeholder="输入注册场所地址" />-->
        <!--        </a-form-model-item>-->
        <!--        <a-form-model-item label="注册固定电话" prop="register_phone">-->
        <!--          <a-input v-model="invoiceForm.register_phone" placeholder="输入注册固定电话" />-->
        <!--        </a-form-model-item>-->
        <a-form-model-item label="申请备注" prop="notes">
          <a-textarea v-model="invoiceForm.notes" placeholder="输入申请备注"></a-textarea>
        </a-form-model-item>
      </a-form-model>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import col from '@/columns/invoice'
import { getMyInvoiceList, getInvoiceNum, SetInvoiceRead } from '@/api/invoice'
import { getEditInvoice, postEditInvoice } from '@/api/contract'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import apis from '@/api'

export default {
  components: {
    STable
  },
  name: 'MyInvoice',
  data () {
    const validateUrl = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('必须上传发票模版'))
      } else {
        callback()
      }
    }
    return {
      invoiceColumns: col.list,
      invoiceForm: {},
      invoiceNum: {},
      invoiceVisible: false,
      companyOpts: {},
      invoiceData: parameters => {
        return getMyInvoiceList(Object.assign(parameters, this.queryParam)).then(res => {
          this.statusOpts = res.result.invoice_status
          this.headerOpts = res.result.header_type_opts
          this.typeOpts = res.result.invoice_type_opts
          return res.result
        })
      },
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      advanced: true,
      queryParam: {},
      statusOpts: {},
      headerOpts: {},
      typeOpts: {},
      selectedRowKeys: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      invoiceRules: {
        company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
        file_url: [{ validator: validateUrl, trigger: 'change' }]
      },
      invoiceRules1: {
        company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
        header_type: [{ required: true, message: '必须选择抬头类型', trigger: 'change' }],
        header: [{ required: true, message: '必须填写发票抬头', trigger: 'blur' }],
        invoice_type: [{ required: true, message: '必须选择发票类型', trigger: 'change' }],
        social_code: [{ required: true, message: '必须填写统一信用代码证', trigger: 'blur' }]
      },
      invoiceRules2: {
        company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
        header_type: [{ required: true, message: '必须选择抬头类型', trigger: 'change' }],
        header: [{ required: true, message: '必须填写发票抬头', trigger: 'blur' }],
        invoice_type: [{ required: true, message: '必须选择发票类型', trigger: 'change' }],
        bank_name: [{ required: true, message: '必须填写开户行', trigger: 'blur' }],
        social_code: [{ required: true, message: '必须填写统一信用代码证', trigger: 'blur' }],
        account_num: [{ required: true, message: '必须填写银行账户', trigger: 'blur' }],
        register_address: [{ required: true, message: '必须填写地址', trigger: 'blur' }],
        register_phone: [{ required: true, message: '必须填写联系电话', trigger: 'blur' }]
      },
      header: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      uploadUrl: apis.Upload
    }
  },
  created () {
    this.queryParam['filter[status]'] = 10
    this.getInvoiceNum()
  },
  methods: {
    getInvoiceNum () {
      getInvoiceNum().then(res => {
        this.invoiceNum = res.result
      })
    },
    toDetail (id) {
      this.$router.push({ name: 'InvoiceDetail', params: { id } })
      SetInvoiceRead(id)
      this.getInvoiceNum()
      this.$refs.table.refresh(true)
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onCreateAt (date, dateString) {
      this.queryParam['filter[created_at_start]'] = dateString[0]
      this.queryParam['filter[created_at_end]'] = dateString[1]
    },
    // onCheckAt (date, dateString) {
    //   this.queryParam['filter[check_time_start]'] = dateString[0]
    //   this.queryParam['filter[check_time_end]'] = dateString[1]
    // },
    resetSearch () {
      // this.queryParam = {}
      // this.queryParam['filter[contract_no]'] = ''
      // this.queryParam['filter[tm_name]'] = ''
       this.queryParam['filter[created_at_start]'] = ''
       this.queryParam['filter[created_at_end]'] = ''
      this.$refs.table.refresh(true)
    },
    onTabs (key) {
      this.queryParam['filter[status]'] = key
      this.$refs.table.refresh(true)
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    editInvoice (id) {
      getEditInvoice(id).then(res => {
        this.invoiceForm = res.result.invoiceData
        this.invoiceForm.invoice_id = id
        this.companyOpts = res.result.company_data
        this.invoiceVisible = true
      })
    },
    onSubmit () {
      const app = this
      const data = {}
      app.$refs.ruleForm.validate(valid => {
        if (valid) {
          for (const k in app.invoiceForm) {
            data['invoice[' + k + ']'] = app.invoiceForm[k]
          }
          postEditInvoice(data, this.invoiceForm.invoice_id).then(res => {
            if (res.status === 0) {
              app.invoiceVisible = false
              app.$refs.table.refresh(true)
              this.getInvoiceNum()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        } else {
          return false
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    onChange (value) {
      const type = this.companyOpts.find(event => event.id === value)
      this.invoiceForm.invoice_type = type.invoice_type.toString()
      this.invoiceForm.company_id = value
    },
    uploadChange (info) {
      if (info.file.status === 'done') {
        this.invoiceForm['file_url'] = info.file.response.result.url
        this.invoiceForm['filename'] = info.file.name
      }
    },
    download (url) {
      window.open('https://design-upload.oss-cn-beijing.aliyuncs.com/template.docx')
    }
    // handleSearch (selectedKeys, confirm, dataIndex) {
    //   confirm()
    //   this.searchText = selectedKeys[0]
    //   this.searchedColumn = dataIndex
    // },
    // handleReset (clearFilters) {
    //   clearFilters()
    // },
  }
}
</script>

<style scoped>
  /deep/.ant-badge-count{right: -7px;top: -3px;}
  #components-badge-demo-dot .anticon-notification {
    width: 16px;
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }
</style>
